const express = require('express');    
const cors = require('cors');          
const cookieParser = require('cookie-parser'); // Cookie解析
const connectDB = require('./config/db'); // 数据库连接
const http = require('http');
const socketIo = require('socket.io');

// 创建Express应用实例
const app = express();
const server = http.createServer(app);
const io = socketIo(server, { cors: { origin: '*' } });

app.set('io', io);

// 配置中间件
app.use(cors({
  origin: true,          
  credentials: true       
}));
app.use(express.json());  
app.use(express.urlencoded({ extended: true })); 
app.use(cookieParser());  


const PORT = 3010;

// 连接MongoDB数据库
connectDB();

// 导入API路由模块
const productRoutes = require('./routes/productRoutes');
const authRoutes = require('./routes/authRoutes');       
const huserRoutes = require('./routes/huser')
const announcementRoutes = require('./routes/AnnouncementRoute'); 
const dingdan = require('./routes/dingdan'); 

const diRoutes = require("./routes/di")
// 注册API路由
app.use('/products', productRoutes); 
app.use('/auth', authRoutes);        
app.use('/huser',huserRoutes)
app.use('/order',dingdan)
app.use('/announcement', announcementRoutes); 
app.use('/di',diRoutes)

io.on('connection', (socket) => {
  socket.on('login', (userId) => {
    socket.join(userId);
  });
});

// 根路由，用于API健康检查
app.get('/', (req, res) => {
  res.send('Zeno电商系统API服务器');
});

// 启动HTTP服务器
server.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
}); 